#include "StdAfx.h"
#include "AudioLocalClient.h"

CAudioLocalClient::CAudioLocalClient(void)
{
	nvrRawImage = 0;
	pAudioPlayer = 0;
}

CAudioLocalClient::~CAudioLocalClient(void)
{
}

void CAudioLocalClient::run()
{
	HANDLE hEvent;
	int nRet;
	int nCount = 0;
	i_prev_atimestamp = 0;
	__int64 next_atimestamp;
	if( nvrRawImage == NULL ) 
		return;
	hEvent = CreateEvent(NULL, FALSE, FALSE, NULL );
	DWORD i_prev_tick =::GetTickCount();
	DWORD i_tick = i_prev_tick;
	DWORD i_wait = 10;
	while( !needExit() )
	{
		i_tick = ::GetTickCount();
		int i_diff = i_tick - i_prev_tick;
		if( i_diff >= 10 )
			i_wait = 1;
		else
			i_wait = 10 - i_diff;
		i_prev_tick = i_tick;

		nRet = ::WaitForSingleObject( hEvent, i_wait );

		if( nRet != WAIT_TIMEOUT )
			break;

		if( needExit() ) break;

		next_atimestamp  = nvrRawImage->atimestamp;
		int i_data_size = nvrRawImage->audio.length;
/*
		Frame new_frame;
		new_frame.format = YUV_FORMAT::yuv_420;
		new_frame.height = nvrRawImage->height;
		new_frame.i_size = i_data_size;
		new_frame.strideY = nvrRawImage->width;
		new_frame.width = nvrRawImage->width;
*/
		int connection = nvrRawImage->videoConnection;

		if(connection == 0 )
		{
			if( nCount++ > (( 33 * 30 )) )
			{
			}
			continue;
		}
		if( i_prev_atimestamp == next_atimestamp ) 
		{
			if( nCount++ > (( 33 * 30 ) ) )	//1 sec
			{
			}
			TRACE(_T("audio[%02d]: timestamp-x now %I64d prev %I64d tick=%d wait=%d\n"),videoInIndex, next_atimestamp, i_prev_atimestamp, i_tick, i_wait );
			continue;
		}
		
		TRACE(_T("audio[%02d]: timestamp now %I64d prev %I64d tick=%d wait=%d\n"),videoInIndex, next_atimestamp, i_prev_atimestamp, i_tick,i_wait );
		i_prev_atimestamp = next_atimestamp;
		nCount = 0;

		if( pAudioPlayer == NULL ) continue;

		char * pData = nvrRawImage->audio.audioData;
		int len = nvrRawImage->audio.length;

		XAUDIOPACKET * pTail = NULL;
		XAUDIOPACKET * pHeader = NULL;

		pTail = new XAUDIOPACKET();
		memset(pTail,0, sizeof(XAUDIOPACKET));

		pTail->channel = 0;
		pTail->fmt = MAKELONG( DEFAULT_PCM_FORMAT, DEFAULT_AUDIO_CODEC ); ;
		pTail->length = len;
		//memcpy(&pTail->time,ftStart,sizeof(FILETIME));
		memcpy( pTail->data, pData, (len>DEFAULT_PACKET_SIZE)?DEFAULT_PACKET_SIZE:len );
		pTail->next = NULL;
		pHeader = pAudioPlayer->Enqueue( pTail );
		if( pHeader )
		{
			delete pHeader;
		}
	}
}